package input

import (
	"m3u8/info"
	"m3u8/util"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"
	"github.com/quangngotan95/go-m3u8/m3u8"
)

type Many struct {
	url string
	count int
	domain string
	playlist *m3u8.Playlist
	items []*m3u8.SegmentItem
}

func (i *Many) GetUrl() string {
	return i.url
}

func (i *Many) GetCount() int {
	return i.count
}

func (i *Many) GetTsNamePattern() string {
	panic("简单模式不支持此方法,请使用Input struct")
}

func (i *Many) Parse(){
	i.url=os.Args[1]

	proxy := func(_ *http.Request) (*url.URL, error) {
		return url.Parse("http://127.0.0.1:8118")//根据定义Proxy func(*Request) (*url.URL, error)这里要返回url.URL
	}
	transport := &http.Transport{Proxy: proxy}
	client:=&http.Client{Transport:transport,Timeout:time.Second*60*10}
	request,err1:=http.NewRequest("GET",i.url,nil)
	if err1!=nil{
		fmt.Println("读取m3u8失败:"+err1.Error())
		os.Exit(1)
	}
	m3u8Response,err:=client.Do(request)
	if err!=nil{
		fmt.Println("读取m3u8失败1:"+err.Error())
		os.Exit(1)
	}
	playlistByte,err2:=ioutil.ReadAll(m3u8Response.Body)
	if err2!=nil{
		fmt.Println("读取m3u8文件失败:"+err2.Error())
		os.Exit(1)
	}
	m3u8String:=string(playlistByte)
	playlist,err3:=m3u8.ReadString(m3u8String)
	i.playlist=playlist
	if err3!=nil{
		fmt.Println("读取列表失败:"+err3.Error())
		os.Exit(1)
	}
	domain,err4:=url.Parse(i.url)
	if err4!=nil{
		fmt.Println("读取URL失败:"+err4.Error())
		os.Exit(1)
	}
	//url
	i.domain=domain.Scheme+"://"+domain.Host
	//items
	i.items=i.playlist.SegmentItems()
	//count
	i.count=len(i.items)
}

func (i *Many) SaveTs(index int,channel chan info.Info){
	now:=time.Now()
	curlUrl:=i.domain+i.items[index].Segment
	urlArr:=strings.Split(curlUrl,"/")
	filename:=strings.Replace(urlArr[len(urlArr)-1],Symbol,strconv.Itoa(index),-1)
	if util.Exists("E:/"+filename){
		channel<-info.Info{Num:index,Msg:filename+"已存在"}
		return
	}

	proxy := func(_ *http.Request) (*url.URL, error) {
		return url.Parse("http://127.0.0.1:8118")//根据定义Proxy func(*Request) (*url.URL, error)这里要返回url.URL
	}
	transport := &http.Transport{Proxy: proxy}

	client:=&http.Client{Transport:transport,Timeout:time.Second*60*10}
	request,err1:=http.NewRequest("GET",curlUrl,nil)
	if err1!=nil{
		channel<-info.Info{Num:index,Msg:err1.Error()}
		return
	}

	request.Header.Add("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36")

	response,err2:=client.Do(request)
	if err2!=nil{
		channel<-info.Info{Num:index,Msg:err2.Error()}
		return
	}

	data, err3 :=ioutil.ReadAll(response.Body)
	if err3!=nil{
		channel<-info.Info{Num:index,Msg:err3.Error()}
		return
	}

	saveFilename:="E:/"+filename
	err4 := ioutil.WriteFile(saveFilename, data, 0777)
	if err4!=nil{
		channel<-info.Info{Num:index,Msg:err4.Error()}
		return
	}

	channel<-info.Info{Num:index,Msg:" "+filename + " success"+" 用时："+util.HumanTime(now)}
	defer response.Body.Close()
}
